package com.google.code.mircle.core.transfers;

import java.io.File;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.github.axet.wget.WGet;
import com.github.axet.wget.info.DownloadError;
import com.github.axet.wget.info.DownloadInfo;
import com.github.axet.wget.info.DownloadRetry;
import com.google.code.mircle.core.Worker;
import com.thoughtworks.xstream.annotations.XStreamAlias;

/**
 * @author axet
 * 
 */
public class EchoRuDownload extends DirectDownload {

    @XStreamAlias("EchoRuDownloadState")
    static class State extends DirectDownload.State {
        boolean parsed;
    }

    State state = new State();

    public EchoRuDownload(URL source, File target) {
        super.state = state;

        this.state.info = new DownloadInfo(source);
        this.state.info.extract();

        this.state.target = target;
        this.state.web = source.toString();
    }

    protected EchoRuDownload() {
    }

    protected Worker.State getState() {
        return super.getState();
    }

    @Override
    public void load(Worker.State s) {
        super.load(s);

        state = (State) s;
    }

    public static boolean handle(String url) {
        return url.indexOf("http://echo.msk.ru/programs") != -1;
    }

    @Override
    public void run() {
        if (!state.parsed) {
            try {
                String str = WGet.getHtml(state.info.getSource(), stop);

                // then stop been caled
                if (str == null)
                    return;

                Pattern p = Pattern.compile("(http://cdn.echo.msk.ru/snd/[^\"]*)");
                Matcher m = p.matcher(str);
                if (!m.find())
                    throw new RuntimeException("download not found");

                state.info = new DownloadInfo(new URL(m.group(1)));
                state.info.extract();

                state.parsed = true;
            } catch (DownloadRetry e) {
                state.ee = e;
                retry();
            } catch (DownloadError e) {
                state.ee = e;
                return;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        changed();

        super.run();
    }

}
